import { load } from 'cheerio'
import type { Element } from 'cheerio'

const fetchTargetText = (url: string): Promise<string> => {
	return new Promise((resolve, reject) => {
		fetch(url)
			.then((r) => r.text())
			.then((res) => {
				resolve(res)
			})
			.catch((e) => {
				reject(e)
			})
	})
}

const resolveText = (text: string) => {
	const $ = load(text)

	let aa = $('meta[property^="og:"]')
	// 正常期望是可以获取到，但是时间 length=0, 已经给官方提了issue

	// 先收集meta的内容
	let metas = $('meta')
		.toArray()
		.map((p: Element) => p.attribs)

	let titleTag = $('title') as unknown as Element

	let title = ''

	// 标题可能不一定存在，因为有点站点没有写 <title>标题</title> 标签
	if (titleTag[0] && titleTag[0].children && titleTag[0].children.length) {
		title = titleTag[0].children[0].data
	}

	// 解析到所有的 script 和 link
	let links = $('link')
		.toArray()
		.map((p: Element) => p.attribs)

	let scripts = $('script')
		.toArray()
		.map((p: Element) => {
			// console.log(p);

			if (p.attribs.src) {
				return p.attribs
			}

			return {
				...p.attribs,
				content: (p.children[0] as unknown as Text).data,
			}
		})

	return {
		metas,
		title,
		links,
		scripts,
	}
}

type TReuslt = {
	metas: Array<any>
	title: string
	links: Array<any>
	scripts: Array<any>
}

/**
 * 解析网站基本信息
 * @param {string} url 目标地址
 * @returns  返回的结果
 */
const resolveSite = async (url: string): Promise<TReuslt> => {
	if (!url || !url.trim()) {
		throw new Error('url地址不能为空')
	}
	console.log('url', url)

	if (!url.trim().startsWith('http') && !url.trim().startsWith('https')) {
		throw new Error('传入的url地址不是 http或者https， 请传入标准的地址')
	}

	let text = await fetchTargetText(url)

	return resolveText(text)
}

// resolveSite('https://space.bilibili.com/3493272492181886').then(r => {
//   console.log(r);
// })

// resolveSite('http://127.0.0.1:8080/01.html').then((r) => {
// 	console.log(r)
// })

export default resolveSite
